package com.jdone.compus.service;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.util.Collections;
import java.util.Map;


@Service
public class WxTokenService {

    @Value("${external.hqfw.wxTokenUrl}")
    private String wxTokenUrl;

    private final RestTemplate restTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public WxTokenService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 从外部接口获取 token。
     * 注意：根据外部接口需要，可在这里构造不同的请求体或 header（如需请求体，请替换掉 body 变量）。
     *
     * @return token 字符串（找不到时返回 null）
     */
    public String fetchWxToken() {
        // --- 构造请求头 ---
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // ----- 请求体：如果接口需要某些 json 参数，请在这里构造 （示例用空对象） -----
        String body = "{}"; // <-- 若接口需要具体参数，请替换此 JSON 字符串

        HttpEntity<String> request = new HttpEntity<>(body, headers);

        ResponseEntity<Map> response = restTemplate.postForEntity(wxTokenUrl, request, Map.class);

        if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
            Map<String, Object> respBody = response.getBody();
            // 常见的 token 字段名：token / access_token
            Object token = respBody.get("data");
            if (token == null) token = respBody.get("accessToken");
            // 若外部接口返回结构更复杂（如 { data: { token: "..." } } ），请根据实际结构调整解析
            if (token != null) {
                return token.toString();
            }
        }
        return null;
    }


    /**
     * 调用微信 ticket 接口并将返回的 JSON 转为 Map
     */
    public Map<String, Object> getTicket(String accessToken, String type) throws Exception {
        if (accessToken == null || accessToken.trim().isEmpty()) {
            throw new IllegalArgumentException("access_token 不能为空");
        }
        if (type == null || type.trim().isEmpty()) {
            type = "jsapi";
        }

        String url = buildWechatUrl(accessToken, type);
        String respJson = restTemplate.getForObject(url, String.class);
        if (respJson == null) {
            return Collections.emptyMap();
        }
        // 将 JSON 转为 Map 返回
        @SuppressWarnings("unchecked")
        Map<String, Object> map = objectMapper.readValue(respJson, Map.class);
        return map;
    }

    private String buildWechatUrl(String accessToken, String type) throws Exception {
        String at = URLEncoder.encode(accessToken, "UTF-8");
        String t = URLEncoder.encode(type, "UTF-8");
        return "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + at + "&type=" + t;
    }
}

